package com.ruoyi.docdraw.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.docdraw.domain.SysProjectSupplier;
import com.ruoyi.docdraw.domain.project.SysProjectVo;
import com.ruoyi.docdraw.service.ISysGDPService;
import com.ruoyi.docdraw.service.ISysProjectSupplierService;
import com.ruoyi.docdraw.service.ISysSupplierService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.docdraw.domain.SysProject;
import com.ruoyi.docdraw.service.ISysProjectService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 项目Controller
 * 
 * @author lvtian
 * @date 2025-04-14
 */
@RestController
@RequestMapping("/docdraw/project")
public class SysProjectController extends BaseController
{
    @Autowired
    private ISysProjectService sysProjectService;

    @Autowired
    private ISysGDPService sysGDPService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysSupplierService sysSupplierService;

    @Autowired
    private ISysProjectSupplierService sysProjectSupplierService;





    @PreAuthorize("@ss.hasPermi('docdraw:project:invite')")
    @PostMapping("/invite/{projectId}")
    @Log(title = "项目邀请供应商", businessType = BusinessType.INSERT)
    public AjaxResult inviteSupplier(@NotNull @PathVariable("projectId") Long projectId, @RequestBody List<Long> suppliers){
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SysProject sysProject = sysProjectService.selectSysProjectByProjectId(projectId);
        if(ObjectUtil.isNull(sysProject)){
            return error("当前项目编号:"+projectId+" 不存在 请检查");
        }
//        Long deptId = user.getDeptId();
//        Long projectDeptId = sysProject.getProjectDeptId();
//        if(!Objects.equals(deptId, projectDeptId)){
//            return error("您不是项目组织的成员");
//        }

        // 已在项目里的供应商 不用多次邀请

        for (Long supplier : suppliers) {
            SysProjectSupplier projectSupplier = new SysProjectSupplier();
            projectSupplier.setProjectId(projectId);
            projectSupplier.setProjectSupplierId(supplier);
            List<SysProjectSupplier> sysProjectSuppliers = sysProjectSupplierService.selectSysProjectSupplierList(projectSupplier);
            if (sysProjectSuppliers.isEmpty()) {
                int i = sysProjectSupplierService.insertSysProjectSupplier(projectSupplier);
            }
        }
        return success("供应商邀请成功");

    }






    /**
     * 查询项目列表
     */
    @PreAuthorize("@ss.hasPermi('docdraw:project:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysProject sysProject)
    {
        startPage();
        List<SysProject> list = sysGDPService.getProject(sysProject, SecurityUtils.getLoginUser().getUser());
        List<SysProjectVo> result = new ArrayList<>();
        for (SysProject project : list) {
            SysProjectVo sysProjectVo = new SysProjectVo();
            BeanUtils.copyBeanProp(sysProjectVo, project);
            Long projectDeptId = project.getProjectDeptId();
            SysDept sysDept = sysDeptService.selectDeptById(projectDeptId);
            sysProjectVo.setDeptName(sysDept.getDeptName());

            Long projectLeaderId = project.getProjectLeaderId();
            SysUser sysUser = sysUserService.selectUserById(projectLeaderId);
            sysProjectVo.setProjectLeaderName(sysUser.getUserName());
            sysProjectVo.setProjectLeaderNickName(sysUser.getNickName());
            result.add(sysProjectVo);
        }
        return getDataTable(result);
    }

    /**
     * 导出项目列表
     */
    @PreAuthorize("@ss.hasPermi('docdraw:project:export')")
    @Log(title = "项目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysProject sysProject)
    {
        startPage();
        List<SysProject> list = sysGDPService.getProject(sysProject, SecurityUtils.getLoginUser().getUser());
        List<SysProjectVo> result = new ArrayList<>();
        for (SysProject project : list) {
            SysProjectVo sysProjectVo = new SysProjectVo();
            BeanUtils.copyBeanProp(sysProjectVo, project);
            Long projectDeptId = project.getProjectDeptId();
            SysDept sysDept = sysDeptService.selectDeptById(projectDeptId);
            sysProjectVo.setDeptName(sysDept.getDeptName());

            Long projectLeaderId = project.getProjectLeaderId();
            SysUser sysUser = sysUserService.selectUserById(projectLeaderId);
            sysProjectVo.setProjectLeaderName(sysUser.getUserName());
            sysProjectVo.setProjectLeaderNickName(sysUser.getNickName());
            result.add(sysProjectVo);
        }

        ExcelUtil<SysProjectVo> util = new ExcelUtil<SysProjectVo>(SysProjectVo.class);
        util.exportExcel(response, result, "项目数据");
    }

    /**
     * 获取项目详细信息
     */
    @PreAuthorize("@ss.hasPermi('docdraw:project:query')")
    @GetMapping(value = "/{projectId}")
    public AjaxResult getInfo(@PathVariable("projectId") Long projectId)
    {
        return success(sysProjectService.selectSysProjectByProjectId(projectId));
    }

    /**
     * 新增项目
     */
    @PreAuthorize("@ss.hasPermi('docdraw:project:add')")
    @Log(title = "项目", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysProject sysProject)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 检查操作人 是否是供应商
        if (sysSupplierService.checkUserIsSupplier(user)) {
            return error("新增项目功能只允许租户操作");
        }
        // 检查同组织下 项目是否重名
        if (!sysProjectService.checkProjectNameUnique(sysProject))
        {
            return error("新增项目'" + sysProject.getProjectName() + "'失败，项目名称已存在");
        }

        // 逻辑修改
        sysProject.setProjectLeaderId(user.getUserId());
        sysProject.setCreateBy(user.getUserName());

        return toAjax(sysProjectService.insertSysProject(sysProject));
    }

    /**
     * 修改项目
     */
    @PreAuthorize("@ss.hasPermi('docdraw:project:edit')")
    @Log(title = "项目", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysProject sysProject)
    {
        // 检查操作人是否为 供应商
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (sysSupplierService.checkUserIsSupplier(user)) {
            return error("修改项目功能只允许租户操作");
        }

        // 检查同组织下 项目是否重名
        if (!sysProjectService.checkProjectNameUnique(sysProject))
        {
            return error("修改项目'" + sysProject.getProjectName() + "'失败，项目名称已存在");
        }
        sysProject.setUpdateBy(user.getUserName());

        int i = sysProjectService.updateSysProject(sysProject);
        String status = sysProject.getStatus();
        // 暂停项目会自动暂停所有子项目
        if(UserConstants.USER_DISABLE.equals(status)){
            sysGDPService.pauseSubProject(sysProject.getProjectId());
        }
        return toAjax(i);
    }

    /**
     * 删除项目
     */
    @PreAuthorize("@ss.hasPermi('docdraw:project:remove')")
    @Log(title = "项目", businessType = BusinessType.DELETE)
	@DeleteMapping("/{projectIds}")
    public AjaxResult remove(@PathVariable Long[] projectIds)
    {
        return toAjax(sysProjectService.deleteSysProjectByProjectIds(projectIds));
    }
}
